package com.jacky.sender;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.sleuth.zipkin2.ZipkinLoadBalancer;
import org.springframework.cloud.sleuth.zipkin2.ZipkinProperties;
import org.springframework.cloud.sleuth.zipkin2.ZipkinRestTemplateCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.web.client.RequestCallback;
import org.springframework.web.client.ResponseExtractor;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import zipkin2.reporter.Sender;

import java.net.URI;
import java.net.URISyntaxException;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: jacky
 * @date: 2018/7/31
 * Time: 9:44
 * Description:
 **/
@Configuration
public class MyZipkinRestTemplateSenderConfiguration {

    @Autowired
    ZipkinUrlExtractor extractor;

    @Bean
    public Sender restTemplateSender(ZipkinProperties zipkin,
                                     ZipkinRestTemplateCustomizer zipkinRestTemplateCustomizer) {
        RestTemplate restTemplate = new ZipkinRestTemplateWrapper(zipkin, this.extractor);
        zipkinRestTemplateCustomizer.customize(restTemplate);
        return new MyRestTemplateSender(restTemplate, zipkin.getBaseUrl(), zipkin.getEncoder());
    }

    @Configuration
    @ConditionalOnMissingClass("org.springframework.cloud.client.loadbalancer.LoadBalancerClient")
    static class DefaultZipkinUrlExtractorConfiguration {
        @Autowired(required = false)
        LoadBalancerClient client;

        @Bean
        @ConditionalOnMissingBean
        ZipkinLoadBalancer noOpLoadBalancer(final ZipkinProperties zipkinProperties) {
            return new ZipkinLoadBalancer() {
                @Override
                public URI instance() {
                    return URI.create(zipkinProperties.getBaseUrl());
                }
            };
        }
    }

    @Configuration
    @ConditionalOnClass(LoadBalancerClient.class)
    static class DiscoveryClientZipkinUrlExtractorConfiguration {

        @Autowired(required = false)
        LoadBalancerClient client;

        @Bean
        @ConditionalOnMissingBean
        ZipkinLoadBalancer loadBalancerClientZipkinLoadBalancer(ZipkinProperties zipkinProperties) {
            return new LoadBalancerClientZipkinLoadBalancer(this.client, zipkinProperties);
        }
    }

    @Bean
    ZipkinUrlExtractor zipkinUrlExtractor(final ZipkinLoadBalancer zipkinLoadBalancer) {
        return new ZipkinUrlExtractor() {
            @Override
            public URI zipkinUrl(ZipkinProperties zipkinProperties) {
                return zipkinLoadBalancer.instance();
            }
        };
    }
}


class ZipkinRestTemplateWrapper extends RestTemplate {

    private static final Log log = LogFactory.getLog(ZipkinRestTemplateWrapper.class);

    private final ZipkinProperties zipkinProperties;
    private final ZipkinUrlExtractor extractor;

    ZipkinRestTemplateWrapper(ZipkinProperties zipkinProperties,
                              ZipkinUrlExtractor extractor) {
        this.zipkinProperties = zipkinProperties;
        this.extractor = extractor;
    }

    @Override
    protected <T> T doExecute(URI originalUrl, HttpMethod method,
                              RequestCallback requestCallback,
                              ResponseExtractor<T> responseExtractor) throws RestClientException {
        URI uri = this.extractor.zipkinUrl(this.zipkinProperties);
        URI newUri = resolvedZipkinUri(originalUrl, uri);
        return super.doExecute(newUri, method, requestCallback, responseExtractor);
    }

    private URI resolvedZipkinUri(URI originalUrl, URI resolvedZipkinUri) {
        try {
            return new URI(resolvedZipkinUri.getScheme(), resolvedZipkinUri.getUserInfo(),
                    resolvedZipkinUri.getHost(), resolvedZipkinUri.getPort(), originalUrl.getPath(),
                    originalUrl.getQuery(), originalUrl.getFragment());
        } catch (URISyntaxException e) {
            if (log.isDebugEnabled()) {
                log.debug("Failed to create the new URI from original ["
                        + originalUrl
                        + "] and new one ["
                        + resolvedZipkinUri
                        + "]");
            }
            return originalUrl;
        }
    }
}


interface ZipkinUrlExtractor {
    URI zipkinUrl(ZipkinProperties zipkinProperties);
}

class LoadBalancerClientZipkinLoadBalancer implements ZipkinLoadBalancer {

    private final LoadBalancerClient loadBalancerClient;
    private final ZipkinProperties zipkinProperties;

    LoadBalancerClientZipkinLoadBalancer(LoadBalancerClient loadBalancerClient,
                                         ZipkinProperties zipkinProperties) {
        this.loadBalancerClient = loadBalancerClient;
        this.zipkinProperties = zipkinProperties;
    }

    @Override
    public URI instance() {
        if (this.loadBalancerClient != null) {
            URI uri = URI.create(this.zipkinProperties.getBaseUrl());
            String host = uri.getHost();
            ServiceInstance instance = this.loadBalancerClient.choose(host);
            if (instance != null) {
                return URI.create(String.format("http://%s:%s", instance.getHost(), instance.getPort()));
            }
        }
        return URI.create(this.zipkinProperties.getBaseUrl());
    }
}


